package chapter10;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2018-03-22 上午9:51
 */
public class ReflectTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReflectTest.class);

    public static void main(String[] args) {
        Date dt = new Date();
        Object obj = dt;
        Class<?> clazz = obj.getClass();
        LOGGER.info(clazz.getName());

        Class<?> clazz2 = Date.class;
        LOGGER.info(clazz2.getName());

        try {
            Class<?> clazz3 = Class.forName("java.util.Date");
            LOGGER.info(clazz3.getName());
            Method[] methods = clazz3.getMethods();
            for (Method method : methods) {
                LOGGER.info("[{}] modifiers:{}", method.getName(), Modifier.toString(method.getModifiers()));
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try {
            Class<?> clazz4 = Class.forName("chapter10.Book");
            Object object = clazz4.newInstance();
            Book book = (Book) object;
            LOGGER.info(book.toString());

            Constructor<?>[] con = clazz4.getConstructors();

            for (Constructor<?> constructor : con) {
                if (constructor.getParameterCount() == 2) {
                    Object object2 = constructor.newInstance("book", 0.0);
                    LOGGER.info(Modifier.toString(constructor.getModifiers()));
                    LOGGER.info(object2.toString());
                }
            }

        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
            e.printStackTrace();
        }


        Class<?> clazz5 = Book.class;
        String fieldName = "title";
        String fieldName2 = "price";
        Method setMethod = null;
        Method setMethod2 = null;
        try {
            setMethod = clazz5.getMethod("set" + initcap(fieldName), String.class);
            setMethod2 = clazz5.getMethod("set" + initcap(fieldName2), double.class);
            Object o = clazz5.newInstance();
            setMethod.invoke(o, "set by invoke");
            setMethod2.invoke(o, 100.0);
            LOGGER.info(o.toString());
        } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
            e.printStackTrace();
        }


    }

    private static String initcap(String name) {
        return name.substring(0, 1).toUpperCase() + name.substring(1);
    }
}
